import { useContext, useEffect, useState } from 'react';
import CancelListIcon from '../../icon/CanceListIcon';
import CancelThumbIcon from '../../icon/CancelThumbIcon';
import { InBizUploadCtx } from '../../../context';
import { isCancelable } from '../../../utils/tool';

interface IProps {
  id: string | number;
  className?: string;
}

const CancelButton = (props: IProps) => {
  const { id, className } = props;
  const { uploader, statusEnum, thumbnail, onItemCancel } = useContext(InBizUploadCtx);
  const [cancelable, setCancelable] = useState(true);
  const removeCustomEvent = () => {
    uploader.off('statusChange', onStatusChange);
  };
  const onStatusChange = (fileId: number, oldStatus: string, newStatus: string) => {
    if (fileId === id) {
      if (!isCancelable(newStatus, statusEnum) && cancelable) {
        setCancelable(false);
      } else if (isCancelable(newStatus, statusEnum) && !cancelable) {
        setCancelable(true);
      } else if (newStatus === statusEnum.DELETED || newStatus === statusEnum.CANCELED) {
        removeCustomEvent();
      }
    }
    const currentFile = uploader.methods.getFile(id);
    if (currentFile?.strategy === 'skip') {
      setCancelable(true);
    }
  };
  const onClick = () => {
    const file = uploader.methods.getFile(id);
    uploader.methods.cancel(id);
    uploader.methods.deleteFile(id);
    onItemCancel && onItemCancel({ id, ...file });
  };
  useEffect(() => {
    uploader.on('statusChange', onStatusChange);
    return () => {
      removeCustomEvent();
    };
  }, [uploader]);
  return cancelable ? (
    <button
      aria-label="cancel"
      className={`react-fine-uploader-cancel-button ${className || ''}`}
      disabled={!cancelable}
      onClick={cancelable ? onClick : undefined}
      type="button"
    >
      {thumbnail ? <CancelThumbIcon /> : <CancelListIcon />}
    </button>
  ) : null;
};

export default CancelButton;
